package com.uenpay.im.ui.old.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.qiyunxin.android.http.cache.HttpStreamCache;
import com.qiyunxin.android.http.common.ImageUtil;
import com.qiyunxin.android.http.listener.OnUploadFileListener;
import com.qiyunxin.android.http.net.HttpRequestAsyncTaskQueue;
import com.qiyunxin.android.http.net.HttpUploadFileAsyncTask;
import com.qiyunxin.android.http.utils.FileUtils;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.weight.choosemorepic.PhotoItem;
import com.qyx.android.weight.view.webview.BridgeHandler;
import com.qyx.android.weight.view.webview.BridgeWebView;
import com.qyx.android.weight.view.webview.CallBackFunction;
import com.qyx.android.weight.view.webview.DefaultHandler;
import com.uenpay.im.LinkDefs;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.choosemorepic.PhotoActivity;
import com.uenpay.im.ui.old.activity.company.EmployeeEntity;
import com.uenpay.im.ui.old.activity.company.OnlyCompanyDeparListActivity;
import com.uenpay.im.ui.old.activity.company.OnlyDepartmentListActivity;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.ImageSize;
import com.uenpay.im.weight.BottomDialog;
import com.uenpay.im.zxing.CaptureActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

@SuppressLint("JavascriptInterface")
public class OaWebViewActivity extends Activity {
	private static final Uri PROFILE_URI = Uri.parse(LinkDefs.MENTIONS_SCHEMA);
	private static final int PAIS = 100;
	private static final int PIC = 101;
	private ArrayList<PhotoItem> select_gl_arr = new ArrayList<PhotoItem>();
	private ArrayList<ImageSize> size = new ArrayList<ImageSize>();
	private BridgeWebView webView;
	private TextView titleTextView;
	private String url;
	private String picPath;
	protected FileUtils fileUtils = new FileUtils(IMApplication.appName);
	private String uploadUrl = "";
	private CallBackFunction photoSelectFunction = null,
			departmentSelectFunction = null, scanFunction;
	private View loading;
	private int entid = 0;
	private TextView no_data;
	private FrameLayout main_content;

	@SuppressLint("InlinedApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// if (android.os.Build.VERSION.SDK_INT >= 14) {
		// getWindow().setFlags(
		// WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
		// WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
		// }
		super.onCreate(savedInstanceState);
		IMApplication.getInstance().addActivity(this);
		setContentView(R.layout.activity_oa_webview);
		url = getIntent().getStringExtra("url");
		entid = getIntent().getIntExtra("entid", 0);
		initView();
		initListener();
		initData();
	}

	@SuppressLint("SetJavaScriptEnabled")
	public void initView() {
		no_data = (TextView) findViewById(R.id.no_data);
		main_content = (FrameLayout) findViewById(R.id.main_content);
		loading = findViewById(R.id.loading);
		webView = (BridgeWebView) findViewById(R.id.webView);
		titleTextView = (TextView) findViewById(R.id.title_textview);
		titleTextView.setText(R.string.app_name);
		webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		webView.setDefaultHandler(new DefaultHandler());
//		webView.clearCache(true);
		webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		webView.setWebViewClient(new WebViewClient() {
//			@Override
//			public void onReceivedError(WebView view, int errorCode,
//					String description, String failingUrl) {
//				if (errorCode == -2) {
//					no_data.setVisibility(View.VISIBLE);
//					main_content.setVisibility(View.GONE);
//				}
//			}
//		});
		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onReceivedTitle(WebView view, String title) {
				if(IMApplication.is_have_network){
					titleTextView.setText(title);
					no_data.setVisibility(View.GONE);
					main_content.setVisibility(View.VISIBLE);
				}else{
					no_data.setVisibility(View.VISIBLE);
					main_content.setVisibility(View.GONE);
				}
			}

			@SuppressWarnings("unused")
			public void openFileChooser(ValueCallback<Uri> uploadMsg,
					String AcceptType, String capture) {
				this.openFileChooser(uploadMsg);
			}

			@SuppressWarnings("unused")
			public void openFileChooser(ValueCallback<Uri> uploadMsg,
					String AcceptType) {
				this.openFileChooser(uploadMsg);
			}

			public void openFileChooser(ValueCallback<Uri> uploadMsg) {
				// mUploadMessage = uploadMsg;
				// pickFile();
			}

		});

		/**
		 * 注册登录信息
		 */
		webView.registerHandler("loginInfoGet", new BridgeHandler() {

			@Override
			public void handler(String data, CallBackFunction function) {
				JSONObject json = new JSONObject();
				try {
					json.put("entId", entid);
					json.put("custId", IMApplication.getCustId());
					json.put("token", IMApplication.getAccessToken());
					function.onCallBack(json.toString());
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});

		webView.registerHandler("call_phone", new BridgeHandler() {

			@Override
			public void handler(String data, CallBackFunction function) {
				if (!TextUtils.isEmpty(data)) {
					try {
						//TODO
						JSONObject json = new JSONObject(data);
						String phone_num = json.optString("phone_num");
						if (!TextUtils.isEmpty(phone_num)) {
							Uri uri = Uri.parse("tel:" + phone_num);
							Intent intent = new Intent();
							intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							intent.setAction(Intent.ACTION_CALL);
							intent.setData(uri);
							startActivity(intent);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		});


		/**
		 */
		webView.registerHandler("updateTitle", new BridgeHandler() {

			@Override
			public void handler(String data, CallBackFunction function) {
				if (!TextUtils.isEmpty(data)) {
					titleTextView.setText(data);
				}
			}
		});

		/**
		 */
		webView.registerHandler("photoSelect", new BridgeHandler() {

			@Override
			public void handler(String data, CallBackFunction function) {

				photoSelectFunction = function;
				if (!TextUtils.isEmpty(data)) {
					try {
						JSONObject json = new JSONObject(data);
						uploadUrl = json.optString("uploadUrl");
						if (!TextUtils.isEmpty(uploadUrl)) {
							showBgDialog();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		});
		/**
		 */
		webView.registerHandler("departmentSelect", new BridgeHandler() {

			@Override
			public void handler(String data, CallBackFunction function) {
				departmentSelectFunction = function;
				// Intent intent = new Intent(OaWebViewActivity.this,
				// AllCompanyListActivity.class);
				// intent.putExtra("myexist", 1);
				// startActivityForResult(intent, 102);
				Intent intent = new Intent();
				intent.setClass(OaWebViewActivity.this,
						OnlyCompanyDeparListActivity.class);
				intent.putExtra("entid", entid);
				intent.putExtra("departid", 0);
				startActivityForResult(intent, 102);
			}
		});
		/**
		 */
		webView.registerHandler("organizationMemberSelect",
				new BridgeHandler() {

					@Override
					public void handler(String data, CallBackFunction function) {
						boolean isRadio = false;
						if(!TextUtils.isEmpty(data)){
							try {
								JSONObject json = new JSONObject(data);
								if(json.has("isRadio")){
									int temp = json.optInt("isRadio");
									if(temp == 1){
										isRadio = true;
									}
								}
								if(json.has("enterpriseId")){
									int tempEntid = json.optInt("enterpriseId");
									if(tempEntid != 0){
										entid = tempEntid;
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
						departmentSelectFunction = function;
						Intent intent = new Intent(OaWebViewActivity.this,
								OnlyDepartmentListActivity.class);
						intent.putExtra("entid", entid);
						intent.putExtra("isRadio", isRadio);
						startActivityForResult(intent, 103);
					}
				});
		/**
		 */
		webView.registerHandler("scan", new BridgeHandler() {

			@Override
			public void handler(String data, CallBackFunction function) {
				scanFunction = function;
				Intent intent = new Intent(OaWebViewActivity.this,
						CaptureActivity.class);
				intent.putExtra("is_result_back", true);
				startActivityForResult(intent, 104);
			}
		});
	}

	public void initListener() {
		findViewById(R.id.back_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						onback();
					}
				});
	}

	private void initData() {

		String url = getIntent().getStringExtra("url");
		if (!TextUtils.isEmpty(url)) {
			webView.loadUrl(url);
		} else {
			Uri uri = getIntent().getData();
			String uid = "";
			if (uri != null
					&& PROFILE_URI.getScheme().equals(uri.getScheme())) {
				// uid = uri.getQueryParameter(Defs.PARAM_UID);
				uid = uri.getQuery();
				uid = uid.substring(uid.indexOf("=") + 1, uid.length());
			}
			if (uid != null
					&& uid.length() > 4 && !uid.substring(0, 4).equalsIgnoreCase("http")) {
				uid = "http://" + uid;
			}
			if (!TextUtils.isEmpty(uid)) {
				webView.loadUrl(uid);
			}
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (webView != null) {
			webView.destroy();
			webView = null;
		}
		IMApplication.getInstance().removeActivity(this);
	}

	@Override
	public void onBackPressed() {
		if (webView != null && webView.canGoBack()) {
			webView.goBack();
		} else {
			finish();
		}
	}

	@SuppressLint("NewApi")
	@Override
	protected void onPause() {
		if (webView != null) {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				webView.onPause();
			} else {
				try {
					webView.getClass().getMethod("onPause")
							.invoke(webView, (Object[]) null);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				}
			}
		}
		super.onPause();
	}

	@SuppressLint("NewApi")
	@Override
	protected void onResume() {
		if (webView != null) {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				webView.onResume();
			} else {
				try {
					webView.getClass().getMethod("onResume")
							.invoke(webView, (Object[]) null);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				}
			}
		}
		super.onResume();
	}

	private void onback() {
		if (webView.canGoBack()) {
			webView.goBack();
			webView.refreshDrawableState();
		} else {
			finish();
		}
	}

	public void showBgDialog() {

		BottomDialog.showBottomDialog(OaWebViewActivity.this, getResources()
						.getString(R.string.take_photo),
				getResources().getString(R.string.take_image), getResources()
						.getString(R.string.cancel), -1,
				new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						size.clear();
						Intent getImageByCamera = new Intent(
								OaWebViewActivity.this, CameraActivity.class);

						size.add(new ImageSize(720, 720, ""));

						Bundle bundle = new Bundle();
						bundle.putSerializable("size", size);
						getImageByCamera.putExtras(bundle);
						startActivityForResult(getImageByCamera, PAIS);
					}
				}, new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						Intent getImage = new Intent(OaWebViewActivity.this,
								PhotoActivity.class);
						getImage.putExtra("max_select_count", 1);
						startActivityForResult(getImage, PIC);

					}
				});

	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			File compressFile = null;
			Bitmap compressBitmap = null;
			switch (requestCode) {
			case PAIS:
				try {
					picPath = data.getStringExtra("big_pic_filename");
					uploadPic();
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case PIC:
				try {

					select_gl_arr.clear();
					select_gl_arr = (ArrayList<PhotoItem>) data
							.getSerializableExtra("gl_arr");

					if (select_gl_arr.size() > 0) {
						for (int i = 0; i < select_gl_arr.size(); i++) {
							String path = select_gl_arr.get(i).getPath();
							compressFile = new File(fileUtils.getAlbumDir(),
									Utils.md5(path) + ".jpg");
							compressBitmap = ImageUtil.CompressImage(path, 90,
									720, 720);
							FileOutputStream fos;
							fos = new FileOutputStream(compressFile);
							compressBitmap.compress(Bitmap.CompressFormat.JPEG,
									80, fos);
							picPath = compressFile.getAbsolutePath();
							uploadPic();
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			case 102:
				String result = data.getStringExtra("departName");
				int departId = data.getIntExtra("departId", 0);
				JSONObject json = new JSONObject();
				try {
					json.put("optionId", departId);
					json.put("optionName", result);
					if (departmentSelectFunction != null) {
						departmentSelectFunction.onCallBack(json.toString());
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				break;
			case 103:
				ArrayList<EmployeeEntity> arraylist = (ArrayList<EmployeeEntity>) data.getSerializableExtra("arraylist");
				if(arraylist != null && arraylist.size() > 0){
					JSONArray jsonArray = new JSONArray();
					for(int i = 0,size = arraylist.size(); i < size;i++){
						EmployeeEntity mEmployeeEntity = arraylist.get(i);
						if (mEmployeeEntity != null) {
							JSONObject orgJson = new JSONObject();

							try {
								orgJson.put("custid", mEmployeeEntity.custid);
								orgJson.put("name", mEmployeeEntity.nickname);
								orgJson.put("position", mEmployeeEntity.position);
								orgJson.put("iconUrl", APIConfiguration
										.getAvatarUrlNormal(mEmployeeEntity.custid,
												PacketType.PERSONAL));
								jsonArray.put(orgJson);
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}
					if (departmentSelectFunction != null) {
						departmentSelectFunction.onCallBack(jsonArray
								.toString());
					}
				}
				EmployeeEntity mEmployeeEntity = (EmployeeEntity) data
						.getSerializableExtra("mEmployeeEntity");
				if (mEmployeeEntity != null) {
					JSONObject orgJson = new JSONObject();

					try {
						orgJson.put("custid", mEmployeeEntity.custid);
						orgJson.put("name", mEmployeeEntity.nickname);
						orgJson.put("position", mEmployeeEntity.position);
						orgJson.put("iconUrl", APIConfiguration
								.getAvatarUrlNormal(mEmployeeEntity.custid,
										PacketType.PERSONAL));
						if (departmentSelectFunction != null) {
							departmentSelectFunction.onCallBack(orgJson
									.toString());
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				break;
			case 104:
				String scanResult = data.getStringExtra("result");
				if (!TextUtils.isEmpty(scanResult) && scanFunction != null) {
					scanFunction.onCallBack(scanResult);
				}
				break;
			default:
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void uploadPic() {
		loading.setVisibility(View.VISIBLE);
		String url = uploadUrl + "?" + APIConfiguration.getCustIdAndToken();
		if (picPath.startsWith("http")) {
			picPath = HttpStreamCache.getInstance().GetFilePath(picPath);
		}
		HttpRequestAsyncTaskQueue.getInstance().AddTask(
				new HttpUploadFileAsyncTask("1", picPath, url, "uploadedFile") {

				}, new OnUploadFileListener() {

					@Override
					public void OnSuccess(String key, String response) {
						loading.setVisibility(View.GONE);
						try {
							JSONObject json = new JSONObject(response);
							JSONObject dataJson = json.optJSONObject("data");
							if (dataJson != null) {
								String file_id = dataJson.optString("fileid");
								String file_hash = dataJson
										.optString("filehash");
								JSONObject jsonObject = new JSONObject();
								jsonObject.put("fileid", file_id);
								jsonObject.put("filehash", file_hash);
								if (photoSelectFunction != null) {
									photoSelectFunction.onCallBack(jsonObject
											.toString());
								}
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void OnFail(String key, String reason) {
						loading.setVisibility(View.GONE);
					}
				});

	}

}
